from rest_framework import viewsets
from rest_framework.decorators import action

from system.models import Encrypt
from system.serializers import EncryptSerializer
from system.services import encrypt_service
from log.services import log_service
from libs.decorators import permission_required
from libs.enums import Permission, LogModule
from libs.simple_responses import api_success


class EncryptViewSet(viewsets.GenericViewSet):
    queryset = Encrypt.objects.all()
    serializer_class = EncryptSerializer
    ordering_fields = ('id',)
    log_module = LogModule.ENCRYPT.value

    @permission_required([Permission.ORGANIZATION_INFO_MANAGE.value])
    @action(methods=['get'], detail=False)
    def query(self, request, *args, **kwargs):
        instance = encrypt_service.get()
        data = EncryptSerializer(instance).data
        return api_success(data=data)

    @permission_required([Permission.ORGANIZATION_INFO_MANAGE.value])
    @action(methods=['post'], detail=False)
    def reset(self, request, *args, **kwargs):
        instance = encrypt_service.reset_encrypt_key()
        log_service.build_update_log(request.user, instance, module=self.log_module, content='重置了企业密钥')
        data = EncryptSerializer(instance).data
        return api_success(data=data)
